package com.ruoyi.ldzlsb.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ldzlsb.domain.SbInspectionDetail;
import com.ruoyi.ldzlsb.domain.SbInspectionPlan;
import com.ruoyi.ldzlsb.domain.SbInspectionRecord;
import com.ruoyi.ldzlsb.domain.SbInspectionConfig;
import com.ruoyi.ldzlsb.mapper.SbInspectionConfigMapper;
import com.ruoyi.ldzlsb.mapper.SbInspectionPlanMapper;
import com.ruoyi.ldzlsb.mapper.SbInspectionRecordMapper;
import com.ruoyi.ldzlsb.service.ISbInspectionRecordService;
import com.ruoyi.ldzlsb.mapper.SbInspectionDetailMapper;

/**
 * 巡检单Service业务层处理
 *
 * @author anli
 * @date 2024-01-01
 */
@Service
public class SbInspectionRecordServiceImpl implements ISbInspectionRecordService
{
    private static final Logger logger = LoggerFactory.getLogger(SbInspectionRecordServiceImpl.class);
    
    @Autowired
    private SbInspectionRecordMapper sbInspectionRecordMapper;

    @Autowired
    private SbInspectionPlanMapper sbInspectionPlanMapper;

    @Autowired
    private SbInspectionConfigMapper sbInspectionConfigMapper;
    
    @Autowired
    private SbInspectionDetailMapper sbInspectionDetailMapper;

    /**
     * 查询巡检单
     *
     * @param recordId 巡检单主键
     * @return 巡检单
     */
    @Override
    public SbInspectionRecord selectSbInspectionRecordByRecordId(Long recordId)
    {
        return sbInspectionRecordMapper.selectSbInspectionRecordByRecordId(recordId);
    }

    /**
     * 查询巡检单列表
     *
     * @param sbInspectionRecord 巡检单
     * @return 巡检单
     */
    @Override
    public List<SbInspectionRecord> selectSbInspectionRecordList(SbInspectionRecord sbInspectionRecord)
    {
        return sbInspectionRecordMapper.selectSbInspectionRecordList(sbInspectionRecord);
    }

    /**
     * 新增巡检单
     *
     * @param sbInspectionRecord 巡检单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSbInspectionRecord(SbInspectionRecord sbInspectionRecord)
    {
        // 设置默认值
        sbInspectionRecord.setCreateBy(SecurityUtils.getUsername());
        sbInspectionRecord.setCreateTime(DateUtils.getNowDate());
        sbInspectionRecord.setUpdateBy(SecurityUtils.getUsername());
        sbInspectionRecord.setUpdateTime(DateUtils.getNowDate());
        sbInspectionRecord.setIsDelete("0");

        // 处理日期格式问题
        try {
            // 记录原始日期字符串，便于调试
            if (sbInspectionRecord.getInspectionStartTime() != null) {
                logger.info("原始巡检开始时间: {}", sbInspectionRecord.getInspectionStartTime());
            }
            
            // 如果开始时间为字符串形式（通过反射检查），尝试转换
            if (sbInspectionRecord.getInspectionStartTime() == null) {
                // 尝试使用inspectionDate + 当前时间作为开始时间
                if (sbInspectionRecord.getInspectionDate() != null) {
                    Date currentTime = DateUtils.getNowDate();
                    // 合并日期和当前时间
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        SimpleDateFormat dateSdf = new SimpleDateFormat("yyyy-MM-dd");
                        String dateStr = dateSdf.format(sbInspectionRecord.getInspectionDate());
                        String timeStr = sdf.format(currentTime).substring(11); // 获取时间部分
                        Date startTime = sdf.parse(dateStr + " " + timeStr);
                        sbInspectionRecord.setInspectionStartTime(startTime);
                        logger.info("使用合成的日期时间: {}", sdf.format(startTime));
                    } catch (Exception e) {
                        logger.error("日期时间格式转换失败", e);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("处理日期格式时出错", e);
        }

        // 生成巡检单号
        if (StringUtils.isEmpty(sbInspectionRecord.getRecordCode())) {
            sbInspectionRecord.setRecordCode(generateRecordCode());
        }

        // 设置默认状态
        if (StringUtils.isEmpty(sbInspectionRecord.getInspectionStatus())) {
            sbInspectionRecord.setInspectionStatus("0"); // 待巡检
        }

        int rows = sbInspectionRecordMapper.insertSbInspectionRecord(sbInspectionRecord);
        insertSbInspectionDetail(sbInspectionRecord);
        return rows;
    }

    /**
     * 修改巡检单
     *
     * @param sbInspectionRecord 巡检单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateSbInspectionRecord(SbInspectionRecord sbInspectionRecord)
    {
        sbInspectionRecord.setUpdateBy(SecurityUtils.getUsername());
        sbInspectionRecord.setUpdateTime(DateUtils.getNowDate());
        
        sbInspectionDetailMapper.deleteSbInspectionDetailByRecordId(sbInspectionRecord.getRecordId());
        insertSbInspectionDetail(sbInspectionRecord);
        return sbInspectionRecordMapper.updateSbInspectionRecord(sbInspectionRecord);
    }

    /**
     * 批量删除巡检单
     *
     * @param recordIds 需要删除的巡检单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSbInspectionRecordByRecordIds(Long[] recordIds)
    {
        sbInspectionDetailMapper.deleteSbInspectionDetailByRecordIds(recordIds);
        return sbInspectionRecordMapper.deleteSbInspectionRecordByRecordIds(recordIds);
    }

    /**
     * 删除巡检单信息
     *
     * @param recordId 巡检单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteSbInspectionRecordByRecordId(Long recordId)
    {
        sbInspectionDetailMapper.deleteSbInspectionDetailByRecordId(recordId);
        return sbInspectionRecordMapper.deleteSbInspectionRecordByRecordId(recordId);
    }

    /**
     * 根据计划ID查询巡检单列表
     *
     * @param planId 巡检计划ID
     * @return 巡检单集合
     */
    @Override
    public List<SbInspectionRecord> selectSbInspectionRecordByPlanId(Long planId)
    {
        SbInspectionRecord query = new SbInspectionRecord();
        query.setPlanId(planId);
        query.setIsDelete("0");
        return sbInspectionRecordMapper.selectSbInspectionRecordList(query);
    }

    /**
     * 根据设备ID查询巡检单列表
     *
     * @param equipmentId 设备ID
     * @return 巡检单集合
     */
    @Override
    public List<SbInspectionRecord> selectSbInspectionRecordByEquipmentId(Long equipmentId)
    {
        SbInspectionRecord query = new SbInspectionRecord();
        query.setEquipmentId(equipmentId);
        query.setIsDelete("0");
        return sbInspectionRecordMapper.selectSbInspectionRecordList(query);
    }

    /**
     * 根据巡检人员ID查询巡检单列表
     *
     * @param inspectorId 巡检人员ID
     * @return 巡检单集合
     */
    @Override
    public List<SbInspectionRecord> selectSbInspectionRecordByInspectorId(Long inspectorId)
    {
        SbInspectionRecord query = new SbInspectionRecord();
        query.setInspectorId(inspectorId);
        query.setIsDelete("0");
        return sbInspectionRecordMapper.selectSbInspectionRecordList(query);
    }

    /**
     * 统计今日巡检单数量
     *
     * @return 今日巡检单数量
     */
    @Override
    public int countTodayInspectionRecords()
    {
        return sbInspectionRecordMapper.countTodayInspectionRecords();
    }

    /**
     * 新增巡检明细信息
     * 
     * @param record 巡检单对象
     */
    private void insertSbInspectionDetail(SbInspectionRecord record)
    {
        List<SbInspectionDetail> sbInspectionDetailList = record.getInspectionDetailList();
        Long recordId = record.getRecordId();
        if (StringUtils.isNotEmpty(sbInspectionDetailList))
        {
            List<SbInspectionDetail> list = new ArrayList<SbInspectionDetail>();
            for (SbInspectionDetail detail : sbInspectionDetailList)
            {
                detail.setRecordId(recordId);
                detail.setCreateBy(record.getCreateBy());
                detail.setCreateTime(DateUtils.getNowDate());
                detail.setUpdateBy(record.getUpdateBy());
                detail.setUpdateTime(DateUtils.getNowDate());
                list.add(detail);
            }
            if (list.size() > 0)
            {
                sbInspectionDetailMapper.batchInsertSbInspectionDetail(list);
            }
        }
    }

    /**
     * 生成巡检单号
     * 
     * @return 巡检单号
     */
    private String generateRecordCode()
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        return "JX" + dateStr + String.format("%03d", (int)(Math.random() * 1000));
    }

    /**
     * 查询巡检单列表（包含关联信息）
     *
     * @param sbInspectionRecord 巡检单
     * @return 巡检单集合
     */
    @Override
    public List<SbInspectionRecord> selectSbInspectionRecordWithInfoList(SbInspectionRecord sbInspectionRecord)
    {
        return sbInspectionRecordMapper.selectSbInspectionRecordWithInfoList(sbInspectionRecord);
    }

    /**
     * 根据巡检单编号查询巡检单
     *
     * @param recordCode 巡检单编号
     * @return 巡检单
     */
    @Override
    public SbInspectionRecord selectSbInspectionRecordByRecordCode(String recordCode)
    {
        return sbInspectionRecordMapper.selectSbInspectionRecordByRecordCode(recordCode);
    }

    /**
     * 检查设备是否正在巡检中
     *
     * @param equipmentId 设备ID
     * @return true表示设备正在巡检中，false表示设备不在巡检中
     */
    @Override
    public boolean checkEquipmentInInspection(Long equipmentId) {
        if (equipmentId == null) {
            return false;
        }
        
        // 创建查询条件
        SbInspectionRecord query = new SbInspectionRecord();
        query.setEquipmentId(equipmentId);
        query.setStatus("1"); // 状态为"巡检中"
        query.setIsDelete("0");
        
        // 查询符合条件的巡检单
        List<SbInspectionRecord> records = sbInspectionRecordMapper.selectSbInspectionRecordList(query);
        
        // 如果存在状态为"巡检中"的巡检单，则返回true
        return records != null && !records.isEmpty();
    }
} 